package com.alvis.media.controller;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.NonStaticResourceHttpRequestHandler;
import com.alvis.media.base.RestResponse;
import com.alvis.media.domain.*;
import com.alvis.media.service.IVideoInfoService;
import com.alvis.media.service.VideoInfoService;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.video.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 传媒管理（视频列表、视频上传）
 */
@RestController("VideoController")
@RequestMapping(value = "/api/admin/video")
@AllArgsConstructor
public class VideoController extends BaseApiController {
    @Autowired
    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    private final VideoInfoService videoInfoService;

    /**
     * 视频创建
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> createVideo(@RequestBody @Valid VideoCreateVM model) {
        // step1 校验视频是否上传 （判断url是否为空）
        if (StringUtils.isBlank(model.getVideoUrl())) {
            return RestResponse.fail(500, "视频文件未上传");
        }

        // 字段映射
        VideoInfo videoInfo = modelMapper.map(model, VideoInfo.class);

        User user = getCurrentUser();     // 获取当前用户
        videoInfo.setCreatorId(user.getId()); // 设置上传视频的作者ID
        videoInfo.setVideoUuid(new Random().nextInt());
        // step2 调用service层做入库操作
        videoInfoService.insertByFilter(videoInfo);

        return RestResponse.ok();
    }

    /**
     * 视频信息列表分页查询
     *
     * @param model 视频分页请求VM
     * @return RestResponse<PageInfo < VideoResponseVM>>　视频分页响应VM
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<VideoResponseVM>> pageList(@RequestBody VideoPageRequestVM model) {
        // 视频分页查询
        PageInfo<VideoInfo> pageInfo = videoInfoService.findVideoInfoPage(model);
        PageInfo<VideoResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> VideoResponseVM.from(d));
        return RestResponse.ok(page);
    }

    /**
     * 视频播放前要先视频查询
     */
    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> select(@PathVariable Integer id) {
        VideoInfo video = videoInfoService.selectById(id);

        videoInfoService.insertVideoPlay(video.getVideoUrl(), getCurrentUser().getId());
        video.setVideoUrl("/api/admin/video/play/" + video.getVideoUrl());

        VideoResponseVM videoVm = VideoResponseVM.from(video);
        return RestResponse.ok(videoVm);
    }

    /**
     * 视频播放
     */
    @GetMapping("/play/**/*")
    public void playVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // realPath 即视频所在的完整地址
        String url = request.getRequestURL().toString();
        int index = url.lastIndexOf("D:");
        String realPath = url.substring(index);

        /*
        if (request.getHeader("Range").equals("bytes-0"))
        {
            videoInfoService.insertVideoPlay(realPath, getCurrentUser().getId());
        }
        */

        Path filePath = Paths.get(realPath);
        if (Files.exists(filePath)) {
            // 利用 Files.probeContentType 获取文件类型
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                // 设置 response
                response.setContentType(mimeType);
            }
            request.setAttribute(nonStaticResourceHttpRequestHandler.filepath, filePath);

            // 利用 ResourceHttpRequestHandler.handlerRequest() 实现返回视频流
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }


    /**
     * 根据视频ID查询视频详细信息
     *
     * @param id 视频ID
     * @return RestResponse<VideoDetailVM>  视频的详情VM
     */
    @RequestMapping(value = "/getVideoDetailByVideoId/{id}", method = RequestMethod.POST)
    public RestResponse<VideoDetailVM> getVideoDetailByVideoId(@PathVariable Integer id) {
        VideoInfo video = videoInfoService.selectById(id);

        VideoDetailVM vm = new VideoDetailVM();
        vm.setVideoName(video.getVideoName());

        List<VideoPlay> videoPlayList = new ArrayList<VideoPlay>();
        VideoPlay videoPlay = new VideoPlay();
        videoPlay.setVideoName("用户" + getCurrentUser().getUserName() + "于 " + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "播放了视频: " + video.getVideoName());
        videoPlayList.add(videoPlay);

        // 视频推荐列表(TODO)
        // List<VideoInfo> videoRecommendList  = new ArrayList<VideoInfo>();
        // vm.setVideoRecommendList(videoRecommendList);

        List<UserVideoOperation> videoOperationList = new ArrayList<UserVideoOperation>();

        List<UserTag> videoTagList = new ArrayList<UserTag>();
        vm.setVideoPlayList(videoPlayList);
        vm.setVideoOperationList(videoOperationList);
        vm.setVideoTagList(videoTagList);

        return RestResponse.ok(vm);
    }


    /**
     * 视频删除
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        // 根据视频ID删除视频信息
        videoInfoService.deleteById(id);
        return RestResponse.ok();
    }

    /**
     * 视频编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> editVideo(@RequestBody @Valid VideoCreateVM videoCreateVM) {
        // step1 校验视频是否上传 （判断url是否为空）
        /*if (StringUtils.isBlank(videoCreateVM.getVideoUrl()))
        {
            return RestResponse.fail(500,"视频文件未上传");
        }*/

        // step2 修改相关视频信息
        // 将 UserCreateVM --> 转换成 User
        VideoInfo videoInfo = modelMapper.map(videoCreateVM, VideoInfo.class);

        videoInfo.setVideoName(videoCreateVM.getVideoName());         // 修改视频名称
        videoInfo.setVideoCategory(videoCreateVM.getVideoCategory()); // 修改视频分类
        videoInfoService.updateVideoInfo(videoInfo);
        VideoResponseVM map = modelMapper.map(videoInfo, VideoResponseVM.class);
        return RestResponse.ok(map);
    }


    /**
     * 传媒数据分析 -- 用户属性分析
     */
    @RequestMapping(value = "/userAnalysis/{id}", method = RequestMethod.POST)
    public RestResponse<UserAnalysisVM> userAnalysis(@PathVariable Integer id) {
        // 调用用户属性分析--分析方法
        List<VideoInfo> recommendVideoList = videoInfoService.userAnalysis(id);
        UserAnalysisVM vm = new UserAnalysisVM();
        vm.setVideoRecommendList(recommendVideoList);
        return RestResponse.ok(vm);
    }
}
